/*
 * @Author: tangyuhui 317972442@qq.com
 * @Date: 2025-09-03 21:39:36
 * @LastEditors: tangyuhui 317972442@qq.com
 * @LastEditTime: 2025-09-04 12:03:42
 */
import { ApiResponse } from "./types";

export interface FilterConfig {
  // 成功状态判断
  successCondition?: (response: any) => boolean;
  // 错误消息提取
  getErrorMessage?: (response: any) => string;
  // 错误代码提取
  getErrorCode?: (response: any) => string | number;
  // 需要重新登录的错误代码
  loginRequiredCodes?: (string | number)[];
  // 重新登录回调
  onLoginRequired?: (errorMsg: string, errorCode?: string | number) => void;
  // 通用错误处理
  onError?: (errorMsg: string, errorCode?: string | number) => void;
}

// 默认配置
const defaultFilterConfig: FilterConfig = {
  successCondition: (response: any) => response.success || response.code === 0,
  getErrorMessage: (response: any) => response.msg || response.errorMsg || 'Unknown error',
  getErrorCode: (response: any) => response.code || response.errorCode,
  loginRequiredCodes: [],
  onError: (errorMsg: string) => console.log(errorMsg)
};

// 创建响应过滤器
export function createResponseFilter(config: FilterConfig = {}) {
  const finalConfig = { ...defaultFilterConfig, ...config };

  return function httpFilter<T = any>(response: ApiResponse<T>): Promise<T> {
    if (finalConfig.successCondition!(response)) {
      return Promise.resolve(response.data as T);
    } else {
      const errorMsg = finalConfig.getErrorMessage!(response);
      const errorCode = finalConfig.getErrorCode!(response);

      // 检查是否需要重新登录
      if (finalConfig.loginRequiredCodes!.includes(errorCode)) {
        if (finalConfig.onLoginRequired) {
          finalConfig.onLoginRequired(errorMsg, errorCode);
        }
      } else if (finalConfig.onError) {
        finalConfig.onError(errorMsg, errorCode);
      }

      return Promise.reject(errorMsg);
    }
  };
}